#!/bin/bash

plot() {
suffix=$1
gnuplot <<EOF
set xlabel "time (s)"

set size 1
set terminal pngcairo size ${width:-1280}, 800
set terminal pngcairo size ${width:-1000}, 600
set terminal pngcairo size ${width:-1280}, ${height:-800}

set output "vmstat-written$suffix.png"
set ylabel "size (MB)"
set grid
plot "vmstat$suffix" using 1:(\$3*4/1024) with points pt 5 title "dirtied", \
     "vmstat$suffix" using 1:(\$4*4/1024) with points pt 7 title "written"

set output "vmstat-dirty$suffix.png"
set ylabel "size (MB)"
unset grid
plot "vmstat$suffix" using 1:(\$5*4/1024) with points pt 5 title "dirty", \
     "vmstat$suffix" using 1:(\$6*4/1024) with points pt 6 title "writeback", \
     "vmstat$suffix" using 1:(\$7*4/1024) with points pt 7 title "unstable", \
     "vmstat$suffix" using 1:(\$8*4/1024) with points pt 4 title "dirty thresh", \
     "vmstat$suffix" using 1:(\$9*4/1024) with points pt 3 title "background thresh"

set output "vmstat-reclaimable$suffix.png"
set ylabel "size (MB)"
set grid
plot "vmstat$suffix" using 1:(\$11*4/1024) with points pt 6 lc rgbcolor "green" title "free", \
     "vmstat$suffix" using 1:(\$12*4/1024) with points pt 5 lc rgbcolor "red"   title "anon", \
     "vmstat$suffix" using 1:(\$13*4/1024) with points pt 7 lc rgbcolor "blue"  title "file", \
     "vmstat$suffix" using 1:(\$14*4/1024) with points pt 4 lc rgbcolor "magenta"  title "slab"

# set output "vmstat-unstable$suffix.png"
# set ylabel "size (MB)"
# plot "vmstat$suffix" using 1:(\$6*4/1024) with points pt 6 title "writeback", \
#      "vmstat$suffix" using 1:(\$7*4/1024) with points pt 7 title "unstable"
EOF
}

plot

lines=$(wc -l vmstat | cut -f1 -d' ')
if [[ $lines -ge 300 ]]; then
	tail -n 100 vmstat > vmstat-100
	plot -100
fi
